package code.lucamarrocco.struts2.rest.sample;

public class RestfulProtocolTester {
	public <R> R post(R resource) {
		stringBuilder.append("POST ").append(uriOf(resource)).append(" ");
		stringBuilder.append("{").append(resource).append("}");
		return resource;
	}

	public <R> R put(R resource) {
		stringBuilder.append("PUT ").append(uriOf(resource)).append(" ");
		stringBuilder.append("{").append(resource).append("}");
		return resource;
	}

	public <R> R get(R resource) {
		stringBuilder.append("GET ").append(uriOf(resource));
		return resource;
	}

	public <R> R delete(R resource) {
		stringBuilder.append("DELETE ").append(uriOf(resource)).append(" ");
		stringBuilder.append("{").append(resource).append("}");
		return resource;
	}

	public String uriOf(Object object) {
		if (object instanceof Person) return clean("/persons/" + ((Person) object).getId());
		if (object instanceof UnitOfWork) return clean("/unitOfWork/" + ((UnitOfWork) object).getId());
		throw new RuntimeException("unable to determine uriof " + object);
	}

	private String clean(String uri) {
		uri = uri.replaceAll("/null$", "");
		uri = uri.replaceAll("/0$", "");
		return uri;
	}

	public static final String update(String string) {
		return "update " + string;
	}

	private UnitOfWork unitOfWork = Autocommit;

	public RestfulProtocolTester using(UnitOfWork unitOfWork) {
		this.unitOfWork = unitOfWork;
		return this;
	}

	public static final UnitOfWork Autocommit = new UnitOfWork();

	public static final RestfulProtocolTester inside(UnitOfWork unitOfWork) {
		return new RestfulProtocolTester().using(unitOfWork);
	}

	private StringBuilder stringBuilder = new StringBuilder();

	@Override
	public String toString() {
		return stringBuilder.toString();
	}
}
